<template>
  <el-radio-group v-model="type">
    <el-radio :label="0">2列</el-radio>
    <el-radio :label="1">3列</el-radio>
    <el-radio :label="2">4列</el-radio>
  </el-radio-group>

  <el-table ref="eltable" :data="tableData" border style="width: 100%" :key="Math.random()">
    <el-table-column type="index" width="50" label="No" fixed> </el-table-column>
    <el-table-column prop="date" label="日期" width="150" fixed> </el-table-column>
    <el-table-column prop="name" label="姓名" width="120"> </el-table-column>
    <el-table-column prop="province" label="省份" width="120"> </el-table-column>
    <el-table-column prop="address" label="地址" minWidth="260"> </el-table-column>
    <el-table-column prop="zip" label="邮编" minWidth="120"> </el-table-column>

    <el-table-column label="操作" fixed="right" :render-header="renderHeader">
      <template #default="scope">
        <div class="optionDiv" style="white-space: nowrap; display: inline-block">
          <el-button type="primary" size="small"> 新增新增 </el-button>
          <el-button type="primary" size="small"> 编辑新 </el-button>
          <el-button v-if="scope.row.type == type" type="primary" size="small"> 移除 </el-button>
          <el-button v-if="scope.row.type == type && type == 2" type="primary" size="small">
            详情
          </el-button>
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
const type = ref(0)

const tableData = [
  {
    date: '2016-05-03',
    name: '王小虎',
    province: '上海',
    address: '上海市普陀区金沙江路 1518 弄',
    zip: 200333,
    type: 1
  },
  {
    date: '2016-05-02',
    name: '王小虎',
    province: '上海',
    address: '上海市普陀区金沙江路 1518 弄',
    zip: 200333,
    type: 2
  },
  {
    date: '2016-05-02',
    name: '王小虎',
    province: '上海',
    address: '上海市普陀区金沙江路 1518 弄',
    zip: 200333,
    type: 2
  }
]

// 表头部重新渲染
function renderHeader({ column }) {
  // 获取操作按钮组的元素
  const opts = document.getElementsByClassName('optionDiv')
  let widthArr: any = []
  // 取操作组的最大宽度
  Array.prototype.forEach.call(opts, function (item) {
    if (item.innerText) {
      widthArr.push(item.offsetWidth)
    }
  })
  // 重新设置列标题及宽度属性
  if (widthArr.length > 0) {
    column.width = Math.max(...widthArr) + 30
    return column.label
  } else {
    column.width = 0
    return column.label
  }
}
</script>
